<template>
  <vue-content>
      <vue-header v-if="vueContent">
        <vue-header-form>
          <!-- <el-menu style="background:#ffffff" mode="horizontal" @select="handleSelect">
            <el-menu-item index="1">处理中心</el-menu-item>
            <el-menu-item index="2">
               我的工作台
            </el-menu-item>
            <el-menu-item index="3">订单管理</el-menu-item>
          </el-menu> -->
          <el-form :inline="true" :model="formFilter" ref="formFilter">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model.trim="formFilter.productName" style="width:150px"></el-input>
            </el-form-item>
            <el-form-item label="商品类型">
              <el-select v-model="formFilter.productType" style="width:120px">
                <el-option label="实物" value="1"></el-option>
                <el-option label="彩票" value="2"></el-option>
                <el-option label="券/虚拟" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品编号" prop="productNo">
              <el-input v-model.trim="formFilter.productNo" style="width:100px"></el-input>
            </el-form-item>
            <el-form-item label="商品类别" prop="categoryNo">
              <!-- <el-select v-model="formFilter.categoryNo" style="width:150px">
                <el-option 
                  v-for="item in CategoryList"
                  :key="item.id"
                  :label="item.categoryName"
                  :value="item.categoryNo"
                ></el-option>
              </el-select> -->
              <el-cascader
                style="width:150px"
                :options="CategoryList"
                :props="cascaderConfig"
                v-model="category"
                :change-on-select="ifSelect"
                @change="categoryChange">
              </el-cascader>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="SearchSubmit('formFilter')">查询</el-button>
              <el-button @click="resetForm('formFilter')">重置</el-button>
            </el-form-item>
            <el-button style="float: right;" type="primary" @click="create">新增</el-button>
          </el-form>
        </vue-header-form>
      </vue-header>
      <vue-body v-if="vueContent">
        <el-table
          v-loading.body="loading"
          :data="tableData"
          border
          style="width: 100%">
          <el-table-column
            prop="productNo"
            label="编号">
          </el-table-column>
          <el-table-column
            prop="productName"
            label="名称">
          </el-table-column>
          <el-table-column
            prop="originalPrice"
            label="售价" width="80">
          </el-table-column>
          <el-table-column
            prop="bazaarPrice"
            label="市场价" width="80">
          </el-table-column>
          <el-table-column
            prop="categoryNo"
            label="类别名称" width="100">
            <template scope="scope">
              {{ scope.row.categoryName }}
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态" width="80">
            <template scope="scope">
              {{ scope.row.status | status }}
            </template>
          </el-table-column>
          <el-table-column
            label="类型" width="90">
            <template scope="scope">
              {{ scope.row.productType | productType }}
            </template>
          </el-table-column>
          <el-table-column
            prop="salePrice"
            label="销售价格" width="80">
          </el-table-column>
          <el-table-column
            prop="freight"
            label="运费" width="80">
          </el-table-column>
          <el-table-column
            label="支付方式" width="100">
            <template scope="scope">
              {{ scope.row.payMethod | payMethod }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template scope="scope">
              <el-button-group>
              <el-button
                :disabled="scope.row.status === '1'?true:false"
                size="small"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button
                :disabled="scope.row.status === '1'?true:false"
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row, tableData)">删除</el-button>
              <el-button
              v-show = "scope.row.status === '1'"
              size="small"
              type="danger"
              @click="soldOut(scope.row.id)">下架</el-button>
              <el-button
                v-show = "scope.row.status === '0'"
                size="small"
                @click="sold(scope.row.id)">上架</el-button>
              <el-button
              size="small"
              type="info"
              @click="handleBanner(scope.$index, scope.row, tableData)">轮播图</el-button>
              <el-button
                size="small"
                type="info"
                @click="handleDetail(scope.$index, scope.row, tableData)">详情</el-button>
                </el-button-group>
            </template>
        </el-table-column>
        </el-table>
      </vue-body>
      <vue-footer v-if="vueContent" style="padding: 5px 0;margin: 0 -5px;float:right;">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size="10"
          layout="total, prev, pager, next"
          :total="pageSize">
        </el-pagination>
      </vue-footer>
      <edit-role
      ref="edit-role"
      @close="editFinish"
      :view="view"
      v-if="view ==='create' || view ==='edit'"/>
    <edit-detail
      ref="edit-detail"
      @close="editFinish"
      :view="view"
      v-if="view ==='detail'"/>
  </vue-content>
</template>

<script>
  import {query, del, queryPro,soldOut,sold,queryAllCategory} from '@/services/product'
  import {RequestError} from '@/services/errors'
  import {deepClone} from '@/utilities/object'
  import EditRole from './edit'
  import EditDetail from './Detail'
  export default {
    name: 'role-table',
    components: {EditRole,EditDetail},
    data: () => ({
      tableData: [],
      vueContent:true,
      currentPage: 1,
      pageSize: 10,
      CategoryList:[],
      category:[],
      formFilter: {
        productName: "",
        productType:"",
        productNo:"",
        categoryNo:""
      },
      ifSelect:true,
      loading: false,
      view: '',
      cascaderConfig: {
				label: 'categoryName',
				value: 'categoryNo',
				children: 'secondLevel'
			},
    }),
    methods: {
      async loadData () {
        this.loading = true
        var categoryLength = this.category.length;
        this.formFilter.categoryNo = this.category[categoryLength-1];
        try {
          let data = await query(Object.assign({currentPage: this.currentPage},{perPage:10}, this.formFilter))
          // debugger
          this.tableData = data.productInfoList
          this.pageSize = parseInt(data.totalResult)
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
      },
      async loadCategory () {
        try {
          let data = await queryAllCategory()
          this.CategoryList = data
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
      },
      async create () {
        this.view = 'create'
        this.vueContent = false;
        await this.$nextTick()
        this.$refs['edit-role'].loadCategory();
        this.$refs['edit-role'].loadCoupon();
        this.$refs['edit-role'].queryTree();
        this.$refs['edit-role'].loadData();
      },
      imgSrc(data){
      	return this.$store.state.imgUrl + data;
      },
      async handleEdit (index, data) {
        // debugger
        this.view = 'edit'
        this.vueContent = false;
        await this.$nextTick()
        this.$refs['edit-role'].dialogFormVisible = true
        this.$refs['edit-role'].loadCategory();
        this.$refs['edit-role'].loadCoupon();
        this.$refs['edit-role'].queryTree();
        this.$refs['edit-role'].loadData();
        try {
          let formData = await queryPro(data.id)
          // debugger
          this.$refs['edit-role'].formData = deepClone(formData)
          if(formData.productType != "4"){
            this.$refs['edit-role'].formData.startDate = ""
            this.$refs['edit-role'].formData.endDate = ""
          }
          this.$refs['edit-role'].imgShow = 'edit'
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
      },
      handleDelete (index, data, rows) {
        this.$confirm(`此操作将删除${data.productName}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await del(data.id)
            this.$message({
              type: 'success',
              message: '已删除'
            })
            rows.splice(index, 1)
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, '提示', {
                type: 'error',
                confirmButtonText: '确定'
              })
            } else {
              throw e
            }
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      async handleBanner (index, data) {
				this.$router.push({
	        path: 'product/proBanner', 
	        name: 'proBanner',
	        query: { 
            productNo: data.productNo
          }
        })
      },
      async soldOut (id) {
        try {
        	let insId = id.toString()
          await soldOut(insId)
          this.$message({
            type: 'success',
            message: '下架成功'
          })
          this.loadData()
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
      },
      async sold (id) {
        try {
        	let insId = id.toString()
          await sold(insId)
          this.$message({
            type: 'success',
            message: '上架成功'
          })
          this.loadData()
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
      },
      async handleDetail (index, data) {
        this.view = 'detail'
        await this.$nextTick()
        this.$refs['edit-detail'].id = data.id
        this.$refs['edit-detail'].loadData()
      },
      handleSelect(key, keyPath) {
        console.log(key, keyPath);
      },
      categoryChange(value){
        // console.log(value);
      },
      SearchSubmit () {
        this.currentPage = 1
        this.loadData()
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
        this.category = []
        this.currentPage = 1
        this.loadData()
      },
      editFinish (needRefresh) {
        this.view = ''
        this.vueContent = true;
        if (needRefresh) {
          this.loadData()
        }
      }
    },
    watch: {
      currentPage (newVal) {
        this.loadData(newVal)
      }
    },
    filters: {
      payMethod (value) {
        return {1: 'RMB', 2: '积分',3:'积分+RMB'}[value]
      },
      productType (value) {
        return {1: '实物', 2: '彩票',3:'券/虚拟',4:'优惠券'}[value]
      },
      status (value) {
        return {0: '下架', 1: '上架'}[value]
      },
      categoryNo (value) {
        return {"001": '虚拟券', "002": '实物', "003": '彩票', "005":'其他'}[value]
      }
    },
    created () {
      this.loadData()
      this.loadCategory()
    }
  }
</script>
